package com.pri.chat.nim.session;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import com.netease.nim.uikit.api.NimUIKit;
import com.netease.nim.uikit.api.model.CreateMessageCallback;
import com.netease.nim.uikit.api.model.recent.RecentCustomization;
import com.netease.nim.uikit.api.model.session.SessionCustomization;
import com.netease.nim.uikit.api.model.session.SessionEventListener;
import com.netease.nim.uikit.api.wrapper.NimMessageRevokeObserver;
import com.netease.nim.uikit.business.session.actions.BaseAction;
import com.netease.nim.uikit.business.session.helper.MessageListPanelHelper;
import com.netease.nim.uikit.business.session.module.IMultiRetweetMsgCreator;
import com.netease.nim.uikit.business.session.module.MsgForwardFilter;
import com.netease.nim.uikit.business.session.module.MsgRevokeFilter;
import com.netease.nim.uikit.business.team.model.TeamExtras;
import com.netease.nim.uikit.business.team.model.TeamRequestCode;
import com.netease.nim.uikit.common.ui.dialog.CustomAlertDialog;
import com.netease.nim.uikit.common.ui.dialog.EasyAlertDialogHelper;
import com.netease.nim.uikit.common.ui.popupmenu.NIMPopupMenu;
import com.netease.nim.uikit.common.ui.popupmenu.PopupMenuItem;
import com.netease.nim.uikit.impl.customization.DefaultRecentCustomization;
import com.netease.nim.uikit.net.SharedHelper;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.Observer;
import com.netease.nimlib.sdk.msg.MsgService;
import com.netease.nimlib.sdk.msg.MsgServiceObserve;
import com.netease.nimlib.sdk.msg.SystemMessageObserver;
import com.netease.nimlib.sdk.msg.attachment.MsgAttachment;
import com.netease.nimlib.sdk.msg.constant.MsgDirectionEnum;
import com.netease.nimlib.sdk.msg.constant.MsgTypeEnum;
import com.netease.nimlib.sdk.msg.constant.SessionTypeEnum;
import com.netease.nimlib.sdk.msg.model.IMMessage;
import com.netease.nimlib.sdk.msg.model.LocalAntiSpamResult;
import com.netease.nimlib.sdk.msg.model.RecentContact;
import com.netease.nimlib.sdk.msg.model.SystemMessage;
import com.netease.nimlib.sdk.robot.model.RobotAttachment;
import com.pri.chat.R;
import com.pri.chat.activity.DTmsgActivity;
import com.pri.chat.activity.OtherPeopleMsgActivity;
import com.pri.chat.activity.RechargeListActivity;
import com.pri.chat.activity.ReleaseDTActivity;
import com.pri.chat.activity.ReleaseJuBaoAcctivity;
import com.pri.chat.activity.VedioMsgActivity;
import com.pri.chat.activity.VipCenterActivity;
import com.pri.chat.activity.WishMsgActivity;
import com.pri.chat.nim.DemoCache;
import com.pri.chat.nim.session.action.FileAction;
import com.pri.chat.nim.session.action.GiftAction;
import com.pri.chat.nim.session.action.GuessAction;
import com.pri.chat.nim.session.action.SImageAction;
import com.pri.chat.nim.session.action.SnapChatAction;
import com.pri.chat.nim.session.extension.CustomAttachParser;
import com.pri.chat.nim.session.extension.CustomAttachment;
import com.pri.chat.nim.session.extension.GiftAttachment;
import com.pri.chat.nim.session.extension.RTSAttachment;
import com.pri.chat.nim.session.extension.RedPacketAttachment;
import com.pri.chat.nim.session.extension.SImageAttachment;
import com.pri.chat.nim.session.extension.ShareAttachment;
import com.pri.chat.nim.session.extension.SnapChatAttachment;
import com.pri.chat.nim.session.extension.StickerAttachment;
import com.pri.chat.nim.session.viewholder.MsgViewHolderDefCustom;
import com.pri.chat.nim.session.viewholder.MsgViewHolderGift;
import com.pri.chat.nim.session.viewholder.MsgViewHolderSImage;
import com.pri.chat.nim.session.viewholder.MsgViewHolderShare;
import com.pri.chat.nim.session.viewholder.MsgViewHolderTip;
import com.vondear.rxtool.RxActivityTool;
import com.vondear.rxtool.view.RxToast;

import java.util.ArrayList;
import java.util.List;

/**
 * UIKit自定义消息界面用法展示类
 */
public class SessionHelper {

    private static final int ACTION_HISTORY_QUERY_PERSIST_CLEAR = 0;

    private static final int ACTION_HISTORY_QUERY_NOT_PERSIST_CLEAR = 1;

    private static final int ACTION_SEARCH_MESSAGE = 2;

    private static final int ACTION_CLEAR_MESSAGE_RECORD = 3;

    private static final int ACTION_CLEAR_MESSAGE_NOT_RECORD = 4;

    private static final int ACTION_CLEAR_P2P_MESSAGE = 5;

    private static SessionCustomization p2pCustomization;

    private static SessionCustomization normalTeamCustomization;

    private static SessionCustomization advancedTeamCustomization;

    private static SessionCustomization myP2pCustomization;

    private static SessionCustomization robotCustomization;

    private static RecentCustomization recentCustomization;

    private static NIMPopupMenu popupMenu;

    private static List<PopupMenuItem> menuItemList;

    public static final boolean USE_LOCAL_ANTISPAM = true;


    public static void init() {
        // 注册自定义消息附件解析器
        NIMClient.getService(MsgService.class).registerCustomAttachmentParser(new CustomAttachParser());
        // 注册各种扩展消息类型的显示ViewHolder
        registerViewHolders();
        // 设置会话中点击事件响应处理
        setSessionListener();
        // 注册消息转发过滤器
        registerMsgForwardFilter();
        // 注册消息撤回过滤器
        registerMsgRevokeFilter();
        // 注册消息撤回监听器
        registerMsgRevokeObserver();

        registerSystemMessageObserver();

        NimUIKit.setCommonP2PSessionCustomization(getP2pCustomization());
//        NimUIKit.setCommonTeamSessionCustomization(getTeamCustomization(null));
        NimUIKit.setRecentCustomization(getRecentCustomization());
    }

    public static void startP2PSession(Context context, String account) {
        startP2PSession(context, account, null);
    }

    public static void startP2PSession(Context context, String account, IMMessage anchor) {
        if (!DemoCache.getAccount().equals(account)) {
            if (NimUIKit.getRobotInfoProvider().getRobotByAccount(account) != null) {
                NimUIKit.startChatting(context, account, SessionTypeEnum.P2P, getRobotCustomization(), anchor);
            } else {
                NimUIKit.startP2PSession(context, account, anchor);
            }
        } else {
            NimUIKit.startChatting(context, account, SessionTypeEnum.P2P, getMyP2pCustomization(), anchor);
        }
    }

    public static void startTeamSession(Context context, String tid) {
        startTeamSession(context, tid, null);
    }

    public static void startTeamSession(Context context, String tid, IMMessage anchor) {
//        NimUIKit.startTeamSession(context, tid, getTeamCustomization(tid), anchor);
    }

    // 打开群聊界面(用于 UIKIT 中部分界面跳转回到指定的页面)
    public static void startTeamSession(Context context, String tid, Class<? extends Activity> backToClass,
                                        IMMessage anchor) {
//        NimUIKit.startChatting(context, tid, SessionTypeEnum.Team, getTeamCustomization(tid), backToClass, anchor);
    }

    private static final String TAG = "SessionHelper";
    // 定制化单聊界面。如果使用默认界面，返回null即可
    private static SessionCustomization getP2pCustomization() {
//        if (p2pCustomization == null) {
            p2pCustomization = new SessionCustomization() {

                // 由于需要Activity Result， 所以重载该函数。
                @Override
                public void onActivityResult(final Activity activity, int requestCode, int resultCode, Intent data) {
                    super.onActivityResult(activity, requestCode, resultCode, data);

                }

                @Override
                public boolean isAllowSendMessage(IMMessage message) {
                    return checkLocalAntiSpam(message);
                }

                @Override
                public MsgAttachment createStickerAttachment(String category, String item) {
                    return new StickerAttachment(category, item);
                }
            };
            // 背景
            //            p2pCustomization.backgroundColor = Color.BLUE;
            //            p2pCustomization.backgroundUri = "file:///android_asset/xx/bk.jpg";
            //            p2pCustomization.backgroundUri = "file:///sdcard/Pictures/bk.png";
            //            p2pCustomization.backgroundUri = "android.resource://com.pri.chat/drawable/bk"
            // 定制加号点开后可以包含的操作， 默认已经有图片，视频等消息了
            ArrayList<BaseAction> actions = new ArrayList<>();
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
//                actions.add(new AVChatAction(AVChatType.AUDIO));
//                actions.add(new AVChatAction(AVChatType.VIDEO));
                actions.add(new GiftAction());
//                actions.add(new SImageAction());
                Log.d(TAG, "getP2pCustomization: "+SharedHelper.readId(DemoCache.getContext()));
                if("女".equals(SharedHelper.readSex(DemoCache.getContext()))){
                    actions.add(new SImageAction());
                }

            }
//            actions.add(new RTSAction());
//            actions.add(new SnapChatAction());
//            actions.add(new GuessAction());
//            actions.add(new FileAction());

//            if (NIMRedPacketClient.isEnable()) {
//                actions.add(new RedPacketAction());
//            }
            p2pCustomization.actions = actions;
            p2pCustomization.withSticker = true;
            // 定制ActionBar右边的按钮，可以加多个
            ArrayList<SessionCustomization.OptionsButton> buttons = new ArrayList<>();
            SessionCustomization.OptionsButton cloudMsgButton = new SessionCustomization.OptionsButton() {

                @Override
                public void onClick(Context context, View view, String sessionId) {
                    initPopuptWindow(context, view, sessionId, SessionTypeEnum.P2P);
                }
            };
            cloudMsgButton.iconId = R.drawable.ic_launcher_background;
            SessionCustomization.OptionsButton infoButton = new SessionCustomization.OptionsButton() {

                @Override
                public void onClick(Context context, View view, String sessionId) {
//                    MessageInfoActivity.startActivity(context, sessionId); //打开聊天信息
                }
            };
            infoButton.iconId = R.drawable.ic_launcher_background;
            buttons.add(cloudMsgButton);
            buttons.add(infoButton);
            p2pCustomization.buttons = buttons;
//        }
        return p2pCustomization;
    }

    private static SessionCustomization getMyP2pCustomization() {
        if (myP2pCustomization == null) {
            myP2pCustomization = new SessionCustomization() {

                // 由于需要Activity Result， 所以重载该函数。
                @Override
                public void onActivityResult(Activity activity, int requestCode, int resultCode, Intent data) {
                    if (requestCode == TeamRequestCode.REQUEST_CODE && resultCode == Activity.RESULT_OK) {
                        String result = data.getStringExtra(TeamExtras.RESULT_EXTRA_REASON);
                        if (result == null) {
                            return;
                        }
                        if (result.equals(TeamExtras.RESULT_EXTRA_REASON_CREATE)) {
                            String tid = data.getStringExtra(TeamExtras.RESULT_EXTRA_DATA);
                            if (TextUtils.isEmpty(tid)) {
                                return;
                            }
                            startTeamSession(activity, tid);
                            activity.finish();
                        }
                    }
                }

                @Override
                public boolean isAllowSendMessage(IMMessage message) {
                    return checkLocalAntiSpam(message);
                }

                @Override
                public MsgAttachment createStickerAttachment(String category, String item) {
                    return new StickerAttachment(category, item);
                }
            };
            // 定制加号点开后可以包含的操作， 默认已经有图片，视频等消息了
            ArrayList<BaseAction> actions = new ArrayList<>();
            actions.add(new SnapChatAction());
            actions.add(new GuessAction());
            actions.add(new FileAction());
            actions.add(new GiftAction());

            if("女".equals(SharedHelper.readSex(DemoCache.getContext()))){
                actions.add(new SImageAction());
            }

            myP2pCustomization.actions = actions;
            myP2pCustomization.withSticker = true;
            // 定制ActionBar右边的按钮，可以加多个
            ArrayList<SessionCustomization.OptionsButton> buttons = new ArrayList<>();
            SessionCustomization.OptionsButton cloudMsgButton = new SessionCustomization.OptionsButton() {

                @Override
                public void onClick(Context context, View view, String sessionId) {
                    initPopuptWindow(context, view, sessionId, SessionTypeEnum.P2P);
                }
            };
            cloudMsgButton.iconId = R.drawable.ic_launcher_background;
            buttons.add(cloudMsgButton);
            myP2pCustomization.buttons = buttons;
        }
        return myP2pCustomization;
    }

    private static boolean checkLocalAntiSpam(IMMessage message) {
        if (!USE_LOCAL_ANTISPAM) {
            return true;
        }
        LocalAntiSpamResult result = NIMClient.getService(MsgService.class).checkLocalAntiSpam(message.getContent(),
                                                                                               "**");
        int operator = result == null ? 0 : result.getOperator();
        switch (operator) {
            case 1: // 替换，允许发送
                message.setContent(result.getContent());
                return true;
            case 2: // 拦截，不允许发送
                return false;
            case 3: // 允许发送，交给服务器
                message.setClientAntiSpam(true);
                return true;
            case 0:
            default:
                break;
        }
        return true;
    }

    private static SessionCustomization getRobotCustomization() {
        if (robotCustomization == null) {
            robotCustomization = new SessionCustomization() {

                // 由于需要Activity Result， 所以重载该函数。
                @Override
                public void onActivityResult(final Activity activity, int requestCode, int resultCode, Intent data) {
                    super.onActivityResult(activity, requestCode, resultCode, data);

                }

                @Override
                public MsgAttachment createStickerAttachment(String category, String item) {
                    return null;
                }
            };
            // 定制ActionBar右边的按钮，可以加多个
            ArrayList<SessionCustomization.OptionsButton> buttons = new ArrayList<>();
            SessionCustomization.OptionsButton cloudMsgButton = new SessionCustomization.OptionsButton() {

                @Override
                public void onClick(Context context, View view, String sessionId) {
                    initPopuptWindow(context, view, sessionId, SessionTypeEnum.P2P);
                }
            };
            cloudMsgButton.iconId = R.drawable.ic_launcher_background;
            SessionCustomization.OptionsButton infoButton = new SessionCustomization.OptionsButton() {

                @Override
                public void onClick(Context context, View view, String sessionId) {
//                    RobotProfileActivity.start(context, sessionId); //打开聊天信息
                }
            };
            infoButton.iconId = R.drawable.ic_launcher_background;
            buttons.add(cloudMsgButton);
            buttons.add(infoButton);
            robotCustomization.buttons = buttons;
        }
        return robotCustomization;
    }

    private static RecentCustomization getRecentCustomization() {
        if (recentCustomization == null) {
            recentCustomization = new DefaultRecentCustomization() {

                @Override
                public String getDefaultDigest(RecentContact recent) {
                    if (recent.getAttachment() instanceof GiftAttachment) {
                        return "[礼物]";
                    }
                    if (recent.getAttachment() instanceof ShareAttachment) {
                        return "[分享]";
                    }
                    if (recent.getAttachment() instanceof SImageAttachment) {
                        return "[私密图片]";
                    }
                    return super.getDefaultDigest(recent);
                }
            };
        }
        return recentCustomization;
    }

//    private static SessionCustomization getTeamCustomization(String tid) {
//        if (normalTeamCustomization == null) {
//            // 定制加号点开后可以包含的操作， 默认已经有图片，视频等消息了
//            final TeamAVChatAction avChatAction = new TeamAVChatAction(AVChatType.VIDEO);
//            TeamAVChatProfile.sharedInstance().registerObserver(true);
//            ArrayList<BaseAction> actions = new ArrayList<>();
//            actions.add(avChatAction);
//            actions.add(new GuessAction());
//            actions.add(new FileAction());
//            if (NIMRedPacketClient.isEnable()) {
//                actions.add(new RedPacketAction());
//            }
//            actions.add(new TipAction());
//            SessionTeamCustomization.SessionTeamCustomListener listener = new SessionTeamCustomization.SessionTeamCustomListener() {
//
//                @Override
//                public void initPopupWindow(Context context, View view, String sessionId,
//                                            SessionTypeEnum sessionTypeEnum) {
//                    initPopuptWindow(context, view, sessionId, sessionTypeEnum);
//                }
//
//                @Override
//                public void onSelectedAccountsResult(ArrayList<String> selectedAccounts) {
//                    avChatAction.onSelectedAccountsResult(selectedAccounts);
//                }
//
//                @Override
//                public void onSelectedAccountFail() {
//                    avChatAction.onSelectedAccountFail();
//                }
//            };
//            normalTeamCustomization = new SessionTeamCustomization(listener) {
//
//                @Override
//                public boolean isAllowSendMessage(IMMessage message) {
//                    return checkLocalAntiSpam(message);
//                }
//            };
//            normalTeamCustomization.actions = actions;
//        }
//        if (advancedTeamCustomization == null) {
//            // 定制加号点开后可以包含的操作， 默认已经有图片，视频等消息了
//            final TeamAVChatAction avChatAction = new TeamAVChatAction(AVChatType.VIDEO);
//            TeamAVChatProfile.sharedInstance().registerObserver(true);
//            ArrayList<BaseAction> actions = new ArrayList<>();
//            actions.add(avChatAction);
//            actions.add(new GuessAction());
//            actions.add(new FileAction());
//            actions.add(new AckMessageAction());
//            if (NIMRedPacketClient.isEnable()) {
//                actions.add(new RedPacketAction());
//            }
//            actions.add(new TipAction());
//            SessionTeamCustomization.SessionTeamCustomListener listener = new SessionTeamCustomization.SessionTeamCustomListener() {
//
//                @Override
//                public void initPopupWindow(Context context, View view, String sessionId,
//                                            SessionTypeEnum sessionTypeEnum) {
//                    initPopuptWindow(context, view, sessionId, sessionTypeEnum);
//                }
//
//
//                @Override
//                public void onSelectedAccountsResult(ArrayList<String> selectedAccounts) {
//                    avChatAction.onSelectedAccountsResult(selectedAccounts);
//                }
//
//                @Override
//                public void onSelectedAccountFail() {
//                    avChatAction.onSelectedAccountFail();
//                }
//            };
//            advancedTeamCustomization = new SessionTeamCustomization(listener) {
//
//                @Override
//                public boolean isAllowSendMessage(IMMessage message) {
//                    return checkLocalAntiSpam(message);
//                }
//            };
//            advancedTeamCustomization.actions = actions;
//        }
//        if (TextUtils.isEmpty(tid)) {
//            return normalTeamCustomization;
//        } else {
//            Team team = TeamDataCache.getInstance().getTeamById(tid);
//            if (team != null && team.getType() == TeamTypeEnum.Advanced) {
//                return advancedTeamCustomization;
//            }
//        }
//        return normalTeamCustomization;
//    }
    private static void registerViewHolders() {
//        NimUIKit.registerMsgItemViewHolder(GuessAttachment.class, MsgViewHolderGuess.class);
        NimUIKit.registerMsgItemViewHolder(CustomAttachment.class, MsgViewHolderDefCustom.class);
        NimUIKit.registerMsgItemViewHolder(GiftAttachment.class, MsgViewHolderGift.class);
        NimUIKit.registerMsgItemViewHolder(SImageAttachment.class, MsgViewHolderSImage.class);
        NimUIKit.registerMsgItemViewHolder(ShareAttachment.class, MsgViewHolderShare.class);

//        NimUIKit.registerMsgItemViewHolder(StickerAttachment.class, MsgViewHolderSticker.class);
//        NimUIKit.registerMsgItemViewHolder(SnapChatAttachment.class, MsgViewHolderSnapChat.class);
//        NimUIKit.registerMsgItemViewHolder(RTSAttachment.class, MsgViewHolderRTS.class);
//        NimUIKit.registerMsgItemViewHolder(MultiRetweetAttachment.class, MsgViewHolderMultiRetweet.class);
        NimUIKit.registerTipMsgViewHolder(MsgViewHolderTip.class);
        registerRedPacketViewHolder();
        registerMultiRetweetCreator();
    }

    private static void registerRedPacketViewHolder() {
//        if (NIMRedPacketClient.isEnable()) {
//            NimUIKit.registerMsgItemViewHolder(RedPacketAttachment.class, MsgViewHolderRedPacket.class);
//            NimUIKit.registerMsgItemViewHolder(RedPacketOpenedAttachment.class, MsgViewHolderOpenRedPacket.class);
//        } else {
//            NimUIKit.registerMsgItemViewHolder(RedPacketAttachment.class, MsgViewHolderUnknown.class);
//            NimUIKit.registerMsgItemViewHolder(RedPacketOpenedAttachment.class, MsgViewHolderUnknown.class);
//        }
    }

    private static void registerMultiRetweetCreator(){
        IMultiRetweetMsgCreator creator = new IMultiRetweetMsgCreator() {
            @Override
            public void create(List<IMMessage> msgList, boolean shouldEncrypt, CreateMessageCallback callback) {
//                MessageHelper.createMultiRetweet(msgList, shouldEncrypt, callback);
            }
        };
        NimUIKit.registerMultiRetweetMsgCreator(creator);
    }

    private static void setSessionListener() {
        SessionEventListener listener = new SessionEventListener() {

            @Override
            public void onAvatarClicked(Context context, IMMessage message) {
                // 一般用于打开用户资料页面
                if (message.getMsgType() == MsgTypeEnum.robot && message.getDirect() == MsgDirectionEnum.In) {
                    RobotAttachment attachment = (RobotAttachment) message.getAttachment();
                    if (attachment.isRobotSend()) {
//                        RobotProfileActivity.start(context, attachment.getFromRobotAccount());
                        RxToast.showToast("点击图像");
                        return;
                    }
                }
//                UserProfileActivity.start(context, message.getFromAccount());
                if(!SharedHelper.readId(context).equals(message.getFromAccount())){
                    Bundle bundle =new Bundle();
                    bundle.putString("id",message.getFromAccount());
                    RxActivityTool.skipActivity(context, OtherPeopleMsgActivity.class,bundle);
                }
            }

            @Override
            public void onAvatarLongClicked(Context context, IMMessage message) {
                // 一般用于群组@功能，或者弹出菜单，做拉黑，加好友等功能
            }

            @Override
            public void onAckMsgClicked(Context context, IMMessage message) {
                // 已读回执事件处理，用于群组的已读回执事件的响应，弹出消息已读详情
//                AckMsgInfoActivity.start(context, message);
            }

            @Override
            public void checkMemberInfo(Context context, String memberId) {
                Bundle bundle =new Bundle();
                bundle.putString("id",memberId);
                RxActivityTool.skipActivity(context, OtherPeopleMsgActivity.class,bundle);
            }

            @Override
            public void openVipActivity(Context context,int type) {
                if(type == 0){
                    RxActivityTool.skipActivity(context, VipCenterActivity.class);
                }else if(type == 5){
                    RxActivityTool.skipActivity(context, RechargeListActivity.class);
                }else if(type == 10){
                    RxActivityTool.skipActivity(context, ReleaseDTActivity.class);
                }
            }

            @Override
            public void openSystemActivity(Context context, String type, String id) {
                if("0".equals(type)){
                    Bundle bundle = new Bundle();
                    bundle.putString("id",id);
                    RxActivityTool.skipActivity(context, DTmsgActivity.class,bundle);
                }else if("1".equals(type)){
                    Bundle bundle = new Bundle();
                    bundle.putString("id",id);
                    RxActivityTool.skipActivity(context, WishMsgActivity.class,bundle);
                }else if("2".equals(type)){
                    Bundle bundle = new Bundle();
                    bundle.putString("id",id);
                    RxActivityTool.skipActivity(context, VedioMsgActivity.class,bundle);
                }else if("3".equals(type)){
                    //系统通知

                }else if("4".equals(type)){
                    //关注人
                    Bundle bundle = new Bundle();
                    bundle.putString("id",id);
                    RxActivityTool.skipActivity(context, OtherPeopleMsgActivity.class,bundle);
                }
            }

            @Override
            public void juBao(Context context, String id) {
                Bundle bundle = new Bundle();
                bundle.putString("id",id);
                bundle.putString("type","3");
                RxActivityTool.skipActivity(context, ReleaseJuBaoAcctivity.class,bundle);
            }
        };
        NimUIKit.setSessionListener(listener);
    }


    /**
     * 消息转发过滤器
     */
    private static void registerMsgForwardFilter() {
        NimUIKit.setMsgForwardFilter(new MsgForwardFilter() {

            @Override
            public boolean shouldIgnore(IMMessage message) {
                if (message.getMsgType() == MsgTypeEnum.custom && message.getAttachment() != null &&
                    (message.getAttachment() instanceof SnapChatAttachment ||
                     message.getAttachment() instanceof RTSAttachment ||
                     message.getAttachment() instanceof RedPacketAttachment)) {
                    // 白板消息和阅后即焚消息，红包消息 不允许转发
                    return true;
                } else if (message.getMsgType() == MsgTypeEnum.robot && message.getAttachment() != null &&
                           ((RobotAttachment) message.getAttachment()).isRobotSend()) {
                    return true; // 如果是机器人发送的消息 不支持转发
                }
                return false;
            }
        });
    }

    /**
     * 消息撤回过滤器
     */
    private static void registerMsgRevokeFilter() {
        NimUIKit.setMsgRevokeFilter(new MsgRevokeFilter() {

            @Override
            public boolean shouldIgnore(IMMessage message) {
                if (message.getAttachment() != null && (
                                                        message.getAttachment() instanceof RTSAttachment ||
                                                        message.getAttachment() instanceof RedPacketAttachment)) {
                    // 视频通话消息和白板消息，红包消息 不允许撤回
                    return true;
                } else if (DemoCache.getAccount().equals(message.getSessionId())) {
                    // 发给我的电脑 不允许撤回
                    return true;
                }
                return false;
            }
        });
    }

    private static void registerMsgRevokeObserver() {
        NIMClient.getService(MsgServiceObserve.class).observeRevokeMessage(new NimMessageRevokeObserver(), true);
    }

    //注册系统通知消息
    private static void registerSystemMessageObserver() {
        NIMClient.getService(SystemMessageObserver.class).observeReceiveSystemMsg(new Observer<SystemMessage>() {
            @Override
            public void onEvent(SystemMessage message) {
                // 收到系统通知，可以做相应操作
                Log.d("MSG11","message");
            }
        }, true);
    }


    private static void initPopuptWindow(Context context, View view, String sessionId,
                                         SessionTypeEnum sessionTypeEnum) {
        if (popupMenu == null) {
            menuItemList = new ArrayList<>();
            popupMenu = new NIMPopupMenu(context, menuItemList, listener);
        }
        menuItemList.clear();
        menuItemList.addAll(getMoreMenuItems(context, sessionId, sessionTypeEnum));
        popupMenu.notifyData();
        popupMenu.show(view);
    }

    private static NIMPopupMenu.MenuItemClickListener listener = item -> {
        switch (item.getTag()) {
            case ACTION_HISTORY_QUERY_PERSIST_CLEAR:
//                MessageHistoryActivity.start(item.getContext(), item.getSessionId(),
//                                             item.getSessionTypeEnum(), true); // 漫游消息查询，被清除的消息也入库
                break;
            case ACTION_HISTORY_QUERY_NOT_PERSIST_CLEAR:
//                MessageHistoryActivity.start(item.getContext(), item.getSessionId(),
//                        item.getSessionTypeEnum(), false); // 漫游消息查询，被清除的消息不入库
                break;
            case ACTION_SEARCH_MESSAGE:
//                SearchMessageActivity.start(item.getContext(), item.getSessionId(), item.getSessionTypeEnum());
                break;
            case ACTION_CLEAR_MESSAGE_RECORD:
                EasyAlertDialogHelper.createOkCancelDiolag(item.getContext(), null, "确定要清空吗？", true,
                                                           new EasyAlertDialogHelper.OnDialogActionListener() {

                                                               @Override
                                                               public void doCancelAction() {
                                                               }

                                                               @Override
                                                               public void doOkAction() {
                                                                   NIMClient.getService(MsgService.class)
                                                                            .clearChattingHistory(
                                                                                    item.getSessionId(),
                                                                                    item.getSessionTypeEnum(),
                                                                                    false);
                                                                   MessageListPanelHelper.getInstance()
                                                                                         .notifyClearMessages(
                                                                                                 item.getSessionId());
                                                               }
                                                           }).show();
                break;
            case ACTION_CLEAR_MESSAGE_NOT_RECORD:
                EasyAlertDialogHelper.createOkCancelDiolag(item.getContext(), null, "确定要清空吗？", true,
                                                            new EasyAlertDialogHelper.OnDialogActionListener() {

                                                                @Override
                                                                public void doCancelAction() {
                                                                }

                                                                @Override
                                                                public void doOkAction() {
                                                                    NIMClient.getService(MsgService.class)
                                                                            .clearChattingHistory(
                                                                                    item.getSessionId(),
                                                                                    item.getSessionTypeEnum(),
                                                                                    true);
                                                                    MessageListPanelHelper.getInstance()
                                                                            .notifyClearMessages(
                                                                                    item.getSessionId());
                                                                }
                                                            }).show();
                break;
            case ACTION_CLEAR_P2P_MESSAGE:
                String title = item.getContext().getString(R.string.message_p2p_clear_tips);
                CustomAlertDialog alertDialog = new CustomAlertDialog(item.getContext());
                alertDialog.setTitle(title);
                alertDialog.addItem("确定", new CustomAlertDialog.onSeparateItemClickListener() {

                    @Override
                    public void onClick() {
                        NIMClient.getService(MsgService.class).clearServerHistory(item.getSessionId(),
                                                                                  item.getSessionTypeEnum());
                        MessageListPanelHelper.getInstance().notifyClearMessages(item.getSessionId());
                    }
                });
                String itemText = item.getContext().getString(R.string.sure_keep_roam);
                alertDialog.addItem(itemText, new CustomAlertDialog.onSeparateItemClickListener() {

                    @Override
                    public void onClick() {
                        NIMClient.getService(MsgService.class).clearServerHistory(item.getSessionId(),
                                                                                  item.getSessionTypeEnum(), false);
                        MessageListPanelHelper.getInstance().notifyClearMessages(item.getSessionId());
                    }
                });
                alertDialog.addItem("取消", new CustomAlertDialog.onSeparateItemClickListener() {

                    @Override
                    public void onClick() {
                    }
                });
                alertDialog.show();
                break;
        }
    };

    private static List<PopupMenuItem> getMoreMenuItems(Context context, String sessionId,
                                                        SessionTypeEnum sessionTypeEnum) {
        List<PopupMenuItem> moreMenuItems = new ArrayList<PopupMenuItem>();
        moreMenuItems.add(new PopupMenuItem(context, ACTION_HISTORY_QUERY_PERSIST_CLEAR, sessionId, sessionTypeEnum,
                                            DemoCache.getContext().getString(R.string.message_history_query_ingore)));
        moreMenuItems.add(new PopupMenuItem(context, ACTION_HISTORY_QUERY_NOT_PERSIST_CLEAR, sessionId, sessionTypeEnum,
                                            DemoCache.getContext().getString(R.string.message_history_query_remember)));
        moreMenuItems.add(new PopupMenuItem(context, ACTION_SEARCH_MESSAGE, sessionId, sessionTypeEnum,
                                            DemoCache.getContext().getString(R.string.message_search_title)));
        moreMenuItems.add(new PopupMenuItem(context, ACTION_CLEAR_MESSAGE_RECORD, sessionId, sessionTypeEnum,
                                            DemoCache.getContext().getString(R.string.message_clear_record)));
        moreMenuItems.add(new PopupMenuItem(context, ACTION_CLEAR_MESSAGE_NOT_RECORD, sessionId, sessionTypeEnum,
                                            DemoCache.getContext().getString(R.string.message_clear_not_record)));
        if (sessionTypeEnum == SessionTypeEnum.P2P) {
            moreMenuItems.add(new PopupMenuItem(context, ACTION_CLEAR_P2P_MESSAGE, sessionId, sessionTypeEnum,
                                                DemoCache.getContext().getString(R.string.message_p2p_clear)));
        }
        return moreMenuItems;
    }
}
